﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using FastReflectionLib;
using Newtonsoft.Json;
using System.Data;
using Newtonsoft.Json.Linq;
using Senparc.Weixin.QY.Entities;
using System.Net;
using System.IO;
using SZHL.UI.AppCode;
using SZHL.Data;

namespace SZHL.UI.API
{
    public class AuthManage : IWsService
    {
        public void ProcessRequest(HttpContext context, ref Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            MethodInfo methodInfo = typeof(AuthManage).GetMethod(msg.Action.ToUpper());
            AuthManage model = new AuthManage();
            methodInfo.FastInvoke(model, new object[] { context, msg, P1, P2, UserInfo });
        }


        public void LOGIN(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            string strPassWord = context.Request["password"] ?? "";

            JH_Auth_UserB BUser = new JH_Auth_UserB();
            int count = BUser.GetEntities(d => d.UserName == UserInfo.User.UserName && d.UserPass == strPassWord && d.IsUse == "Y").Count();
            if (count == 0)
            {
                msg.ErrorMsg = "用户名或密码错误";
            }

        }
        public void MODIFYPWD(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            if (P1 == P2)
            {
                P1 = CommonHelp.GetMD5(P1);
                new JH_Auth_UserB().UpadteMiMa(UserInfo.User.UserName, P1);
            }
            else
            {
                msg.ErrorMsg = "确认密码不一致";
            }
        }
        /// <summary>
        /// 获取前端需要的人员选择列表
        /// </summary>
        public void GETUSERJS(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            DataTable dtUsers = new JH_Auth_UserB().GetDTByCommand(" SELECT UserName,UserRealName FROM JH_Auth_User");
            //获取选择用户需要的HTML和转化用户名需要的json数据
            msg.Result = dtUsers;
        }



        /// <summary>
        /// 获取用户树
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1">部门ID</param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void GETUSERTREE(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            List<JH_Auth_BranchB.BranchUser> ListID = new List<JH_Auth_BranchB.BranchUser>();
            string lvl = new JH_Auth_UserB().GetUserLevel(UserInfo.UserRoleCode);
            if (lvl == "1") //部门经理，只看到本部门
            {
                msg.Result = new JH_Auth_BranchB().GetUserTREE(UserInfo.User.BranchCode);
            }
            else if (lvl == "2") //高级人员，看所有部门
            {
                msg.Result = new JH_Auth_BranchB().GetUserTREE(1);
            }
            else  //看自己
            {
                //List<JH_Auth_Branch> ListAll = new JH_Auth_BranchB().GetEntities().ToList();
                //JH_Auth_Branch Branch = new JH_Auth_BranchB().GetEntity(d => d.DeptCode == UserInfo.User.BranchCode);
                //JH_Auth_BranchB.BranchUser Model = new JH_Auth_BranchB.BranchUser();
                //Model.BranchName = Branch.DeptName;
                //Model.BranchID = Branch.DeptCode;
                //Model.SubUsers = new JH_Auth_UserB().GetEntities(d => d.BranchCode == Branch.DeptCode && d.UserName == UserInfo.User.UserName).ToList();
                ////Model.SubBranch = new JH_Auth_BranchB().GETNEXTFLODER(Branch.DeptCode, ListAll);
                ////return Model;

                //msg.Result = Model;
            }
        }

        /// <summary>
        /// 获取用户
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void GETQUERYUSER(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            List<JH_Auth_BranchB.BranchUser> ListID = new List<JH_Auth_BranchB.BranchUser>();
            string lvl = new JH_Auth_UserB().GetUserLevel(UserInfo.UserRoleCode);
            if (lvl == "1") //部门经理，只看到本部门
            {
                msg.Result = new JH_Auth_BranchB().GetQueryUsers(UserInfo.User.BranchCode);
            }
            else if (lvl == "2") //高级人员，看所有部门
            {
                msg.Result = new JH_Auth_BranchB().GetQueryUsers(1);
            }
            else
            {
                msg.Result = "";
            }
        }



        public void GETPMENU(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            DataTable dt = new JH_Auth_MenuB().GetMainMenuByUserName(UserInfo.User.UserName);
            msg.Result = dt;
        }
        /// <summary>
        /// 获取二级菜单
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P">一级菜单ID</param>
        /// <param name="strUserName"></param>
        public void GETMENU(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            DataTable dt = new JH_Auth_MenuB().GetChiMenuByUserName(UserInfo.User.UserName, P1);
            msg.Result = dt;
        }

        public void GETLISTDATA(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            JH_Auth_FormBase FormBaseData = new JH_Auth_FormBaseB().GetEntity(d => d.FormCode == P1);

            string strFormTable = FormBaseData.FormTable;
            if (!string.IsNullOrEmpty(FormBaseData.FormGetSQL))
            {
                strFormTable = " (" + FormBaseData.FormGetSQL + ") as Form ";
            }
            DataTable dtResult = new DataTable();
            dtResult = new JH_Auth_FormBaseB().GetDTByCommand(" select  * from  " + strFormTable + " where 1=1  ORDER BY ID DESC");
            msg.Result = dtResult;
        }
        /// <summary>
        /// 根据部门编号获取部门人员
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void GETUSERBYCODE(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            int deptCode = 0;
            if (!int.TryParse(P1, out deptCode))
            {
                deptCode = 1;
            }
            msg.Result = new JH_Auth_UserB().GetUserListbyBranch(deptCode, P2);
        }
        /// <summary>
        /// 获取部门列表
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void GETBRANCH(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            int deptCode = 0;
            if (!int.TryParse(P1, out deptCode))
            {
                deptCode = -1;
            }
            msg.Result = new JH_Auth_BranchB().GetBranchListByCode(deptCode);
        }
        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void GETROLE(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            string strWhere = " where r.PRoleCode<>-1";
            if (P1 != "")
            {
                strWhere = string.Format(" where  r.roleType='{0}'", P1);
                if (P2 != "")
                {
                    msg.Result1 = new JH_Auth_BranchB().GetEntity(d => d.DeptCode == int.Parse(P2));
                }
            }
            DataTable dt = new JH_Auth_RoleB().GetDTByCommand(@" select r.RoleCode,r.RoleName,r.isSysRole,COUNT(distinct u.UserName) userCount from JH_Auth_Role r left join JH_Auth_UserRole ur on r.RoleCode=ur.RoleCode
                                                               left join JH_Auth_User u on ur.UserName=u.UserName " + strWhere + " group by r.RoleCode,r.RoleName,r.isSysRole ");

            msg.Result = dt;

        }

        public void EDITROLE(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            JH_Auth_Role role = new JH_Auth_Role();
            role = JsonConvert.DeserializeObject<JH_Auth_Role>(P1);
            if (role.RoleCode != 0)
            {
                if (!new JH_Auth_RoleB().Update(role))
                {
                    msg.ErrorMsg = "修改角色失败";
                }

            }
            else
            {
                JH_Auth_Role user1 = new JH_Auth_RoleB().GetEntity(d => d.RoleName == role.RoleName);
                if (user1 != null)
                {
                    msg.ErrorMsg = "角色已存在";
                    return;
                }
                role.isSysRole = "N";
                if (!new JH_Auth_RoleB().Insert(role))
                {
                    msg.ErrorMsg = "添加角色失败";
                }
            }
            if (P2 != "" && msg.ErrorMsg == "")
            {
                try
                {
                    new JH_Auth_UserRoleB().Delete(d => d.RoleCode == role.RoleCode);
                    foreach (string name in P2.Split(','))
                    {
                        string strSQL = string.Format("INSERT INTO  [JH_Auth_UserRole] ([UserName]  ,[RoleCode]) VALUES  ('{0}'  ,'{1}')", name, role.RoleCode);
                        new JH_Auth_UserRoleB().ExsSql(strSQL);
                    }
                }
                catch (Exception ex)
                {
                    msg.ErrorMsg = ex.Message;
                }
            }

        }
        public void DELROLE(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            new JH_Auth_RoleB().delRole(int.Parse(P1));
            msg.ErrorMsg = "";
        }
        public void GETROLEBYCODE(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            msg.Result = new JH_Auth_RoleB().GetEntity(d => d.RoleCode.ToString() == P1);
            msg.Result1 = new JH_Auth_UserRoleB().GetEntities(d => d.RoleCode.ToString() == P1).Select(d => d.UserName).ToList().ListTOString(',');
        }
        /// <summary>
        /// 获取角色列表用户
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void GETROLEUSER(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            DataTable dt = new JH_Auth_RoleB().GetDTByCommand(" select RoleCode,RoleName,RoleDec from JH_Auth_Role where RoleCode=" + P1);
            dt.Columns.Add("UserRoleList", Type.GetType("System.Object"));
            DataTable dtUserRole = new JH_Auth_UserB().GetDTByCommand(@"select DISTINCT u.*,r.RoleCode from JH_Auth_User u inner join dbo.JH_Auth_UserRole ur on   u.Username=ur.UserName
                                        inner join JH_Auth_Role r on ur.RoleCode=r.RoleCode ");
            foreach (DataRow row in dt.Rows)
            {
                DataTable dtUserRole1 = dtUserRole.FilterTable(" RoleCode=" + P1);
                row["UserRoleList"] = dtUserRole1;


            }
            msg.Result = dt;
        }

        /// <summary>
        /// 添加部门
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1">部门名称</param>
        /// <param name="P2">部门描述</param>
        /// <param name="strUserName"></param>
        public void ADDBRANCH(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            JH_Auth_Branch branch = new JH_Auth_Branch();
            branch = JsonConvert.DeserializeObject<JH_Auth_Branch>(P1);
            if (branch.DeptCode == 0)
            {
                JH_Auth_Branch branch1 = new JH_Auth_BranchB().GetEntity(d => d.DeptName == branch.DeptName);
                if (branch1 != null)
                {
                    msg.ErrorMsg = "部门已存在";
                    return;
                }
                branch.Remark1 = new JH_Auth_BranchB().GetBranchNo(branch.DeptRoot);
                if (!new JH_Auth_BranchB().Insert(branch))
                {
                    msg.ErrorMsg = "添加部门失败";
                }
                else
                {
                    try
                    {
                        WXHelp.BranchMangner.WX_CreateBranch(branch);
                    }
                    catch (Exception ex)
                    {
                        new JH_Auth_BranchB().Delete(branch);
                        msg.ErrorMsg = "添加部门失败（微信）";
                    }
                }
            }
            else
            {
                try
                {
                    try
                    {
                        branch.Remark1 = new JH_Auth_BranchB().GetBranchNo(branch.DeptRoot);
                        WXHelp.BranchMangner.WX_UpdateBranch(branch);
                    }
                    catch (Exception ex)
                    {
                        msg.ErrorMsg = "修改部门失败（微信）";
                        return;

                    }
                    if (!new JH_Auth_BranchB().Update(branch))
                    {
                        msg.ErrorMsg = "修改部门失败";
                    }
                }
                catch (Exception ex)
                {
                    msg.ErrorMsg = "修改部门失败";
                }

            }
        }

        /// <summary>
        /// 删除部门
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1">用户名</param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void DELBRANCH(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {

            try
            {
                if (new JH_Auth_UserB().GetEntities(d => d.BranchCode.ToString() == P1).ToList().Count > 0)
                {
                    msg.ErrorMsg = "本部门中存在用户，请先删除用户";
                    return;
                }
                try
                {
                    WXHelp.BranchMangner.WX_DelBranch(P1);
                }
                catch (Exception ex)
                {
                    msg.ErrorMsg = "删除部门失败(微信)";
                    return;
                }

                if (!new JH_Auth_BranchB().Delete(d => d.DeptCode.ToString() == P1))
                {
                    msg.ErrorMsg = "删除部门失败";
                }
            }
            catch (Exception ex)
            {
                msg.ErrorMsg = "删除部门失败";
            }

        }
        /// <summary>
        /// 获取部门信息
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void GETBRANCHBYCODE(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            int code = int.Parse(P1);
            msg.Result = new JH_Auth_BranchB().GetEntity(d => d.DeptCode == code);
        }
        /// <summary>
        /// 添加人员
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void ADDUSER(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            JH_Auth_User user = new JH_Auth_User();
            user = JsonConvert.DeserializeObject<JH_Auth_User>(P1);
            if (user.ID != 0)
            {
                try
                {
                    WXHelp.BranchMangner.WX_UpdateUser(user);

                }
                catch (Exception ex)
                {
                    msg.ErrorMsg = "修改用户失败（微信）" + ex.Message;
                    return;
                }
                if (!new JH_Auth_UserB().Update(user))
                {
                    msg.ErrorMsg = "修改用户失败";
                }
            }
            else
            {
                JH_Auth_User user1 = new JH_Auth_UserB().GetEntity(d => d.UserName == user.UserName);
                if (user1 != null)
                {
                    msg.ErrorMsg = "用户已存在";
                    return;
                }
                user.UserPass = CommonHelp.GetMD5(user.UserPass);
                if (!new JH_Auth_UserB().Insert(user))
                {
                    msg.ErrorMsg = "添加用户失败";
                }
                else
                {
                    try
                    {
                        WXHelp.BranchMangner.WX_CreateUser(user);
                    }
                    catch (Exception ex)
                    {
                        new JH_Auth_UserB().Delete(user);
                        msg.ErrorMsg = "添加用户失败（微信）" + ex.Message;
                    }

                    string strSql = string.Format(@"INSERT into JH_Auth_UserRole (UserName,RoleCode)
                                                        SELECT {0}, RoleCode  from JH_Auth_Role where RoleName='{0}';
                                                    INSERT into JH_Auth_UserRole (UserName,RoleCode) Values({0},3)", user.UserName, user.zhiwu);
                    new JH_Auth_RoleB().ExsSql(strSql);

                }
            }

        }
        /// <summary>
        /// 更改用户是否禁用的状态
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1">用户名</param>
        /// <param name="P2">状态</param>
        /// <param name="strUserName"></param>
        public void UPDATEUSERISUSE(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            JH_Auth_User UPUser = new JH_Auth_UserB().GetEntities(d => d.UserName == P1).SingleOrDefault();
            UPUser.IsUse = P2;
            if (!new JH_Auth_UserB().Update(UPUser))
            {
                msg.ErrorMsg = "更新失败";
            }
            WXHelp.BranchMangner.WX_UpdateUser(UPUser);//为了更新微信用户状态
        }
        /// <summary>
        /// 根据用户删除用户
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1">用户名</param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void DELUSER(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            JH_Auth_User delUser = new JH_Auth_UserB().GetEntity(d => d.UserName == P1);
            try
            {
                JH_Auth_Branch branch = new JH_Auth_BranchB().GetEntity(d => d.DeptCode == delUser.BranchCode);
                if (branch.DeptName != "代理商")
                {
                    WXHelp.BranchMangner.WX_DelUser(P1);
                }
            }
            catch (Exception ex)
            {
                msg.ErrorMsg = P1 + "删除失败(微信)";
                return;
            }
            if (!new JH_Auth_UserB().Delete(d => d.UserName == P1))
            {
                msg.ErrorMsg = P1 + "删除失败";
            }
        }
        public void GETUSERBYUSERNAME(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            JH_Auth_User userModel = new JH_Auth_UserB().GetEntity(d => d.UserName == P1);
            msg.Result = userModel;
            msg.Result1 = new JH_Auth_BranchB().GetBranchNameByCode(userModel.BranchCode);
            msg.Result2 = UserInfo.UserRoleCode;
        }

        /// <summary>
        /// 根据用户名获取用户列表（多个用户以逗号隔开）
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void GETUSERSBYUSERNAME(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {

            msg.Result = new JH_Auth_UserB().GetEntities(d => P1.Split(',').Contains(d.UserName));
        }
        /// <summary>
        /// 获取应用列表
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void GETAPPLIST(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            msg.Result = new JH_Auth_FormBaseB().GetEntities();
        }
        /// <summary>
        /// 修改应用微信信息
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1">修改的json</param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void MODIFYAPPINFO(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            List<JH_Auth_FormBase> formBaseList = JsonConvert.DeserializeObject<List<JH_Auth_FormBase>>(P1);
            foreach (JH_Auth_FormBase formBase in formBaseList)
            {
                new JH_Auth_FormBaseB().Update(formBase);
            }
        }
        /// <summary>
        /// 获取企业信息
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void GETCOMPANYINFO(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            msg.Result = new JH_Auth_QYB().GetEntities().FirstOrDefault();
        }
        /// <summary>
        /// 添加或编辑企业信息
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void EDITCOMPANY(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            JH_Auth_QY company = new JH_Auth_QY();
            company = JsonConvert.DeserializeObject<JH_Auth_QY>(P1);
            if (company.ID != 0)
            {
                if (!new JH_Auth_QYB().Update(company))
                {
                    msg.ErrorMsg = "修改企业信息失败";
                }
            }
            else
            {
                JH_Auth_QY company1 = new JH_Auth_QYB().GetEntity(d => d.QYName == company.QYName);
                if (company1 != null)
                {
                    msg.ErrorMsg = "企业名称已存在";
                    return;
                }
                company.CRUser = "Admin";
                company.CRDate = DateTime.Now;
                if (!new JH_Auth_QYB().Insert(company))
                {
                    msg.ErrorMsg = "添加企业信息失败";
                }
            }
        }
        public void EDITCOMPANYQYH(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            JH_Auth_QY company = JsonConvert.DeserializeObject<JH_Auth_QY>(P1);

            if (!new JH_Auth_QYB().Update(company))
            {
                msg.ErrorMsg = "修改企业号信息失败";
            }
        }


        /// <summary>
        /// 获取部门列表（选人页面使用）
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void GETALLBMLIST(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            DataTable dtBMS = new JH_Auth_BranchB().GetBranchListByCode(int.Parse(P1));
            dtBMS.Columns.Add("xsbm", Type.GetType("System.Object"));
            for (int i = 0; i < dtBMS.Rows.Count; i++)
            {
                dtBMS.Rows[i]["xsbm"] = new JH_Auth_BranchB().GetBranchListByCode(int.Parse(dtBMS.Rows[i]["DeptCode"].ToString()));
            }
            msg.Result = dtBMS;
        }
        /// <summary>
        /// 获取部门列表（页面查询权限使用）
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void GETALLBMUSERLIST(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            DataTable dtBMS = new DataTable();
            string lvl = new JH_Auth_UserB().GetUserLevel(UserInfo.UserRoleCode);

            string strUserTree = "";
            if (lvl == "1") //部门经理，只看到本部门
            {
                strUserTree = "[" + new JH_Auth_BranchB().GetBranchUserTree(UserInfo.User.BranchCode).TrimEnd(',') + "]";
            }
            else if (lvl == "2")
            {
                strUserTree = "[" + new JH_Auth_BranchB().GetBranchUserTree("", -1).TrimEnd(',') + "]";
            }

            msg.Result = strUserTree;
        }
        /// <summary>
        /// 获取部门列表（选择人员页面使用）
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void GETALLBMUSERLISTNEW(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            DataTable dtBMS = new DataTable();
            string lvl = new JH_Auth_UserB().GetUserLevel(UserInfo.UserRoleCode);

            string strUserTree = "";
            if (lvl == "2" || P1 == "Y")
            {
                strUserTree = "[" + new JH_Auth_BranchB().GetBranchTree(-1).TrimEnd(',') + "]";
            }
            else if (lvl == "1") //部门经理，只看到本部门
            {
                strUserTree = "[" + new JH_Auth_BranchB().GetBranchTreeNew(UserInfo.User.BranchCode).TrimEnd(',') + "]";
            }
            else
            {
                strUserTree = "[" + new JH_Auth_BranchB().GetBranchTreeNew(UserInfo.User.BranchCode).TrimEnd(',') + "]";
            }

            msg.Result = strUserTree;
            msg.Result1 = UserInfo.User.BranchCode;
        }


        /// <summary>
        /// 根据部门编号获取部门人员
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void GETUSERBYCODENEW(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            int deptCode = 0;
            if (!int.TryParse(P1, out deptCode))
            {
                deptCode = 1;
            }
            DataTable dtUser = new JH_Auth_UserB().GetUserListbyBranch(deptCode, "");
            msg.Result = dtUser;
        }

        public void GETWXUSER(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            string lvl = new JH_Auth_UserB().GetUserLevel(UserInfo.UserRoleCode);
            int dept = 0;
            if (lvl == "2" || P1 == "Y")
            {
                dept = 1;
            }
            else {
                dept = UserInfo.User.BranchCode;
            }
            List<WXUserBR> list = new List<WXUserBR>();
            var listALL = new JH_Auth_BranchB().GetEntities().ToList();
            //var list0 = listALL.Where(p => p.DeptRoot == 1).OrderBy(p => p.DeptShort).ToList();
            var list0 = listALL.Where(p => p.DeptCode == dept).OrderBy(p => p.DeptShort).ToList();
            foreach (var v in list0)
            {
                WXUserBR wx = new WXUserBR();
                wx.DeptCode = v.DeptCode;
                wx.DeptName = v.DeptName;
                wx.DeptUser = new JH_Auth_UserB().GetEntities(d => d.BranchCode == v.DeptCode).ToList().Select(d => new { d.ID, d.UserName, d.UserRealName, d.telphone, d.mobphone, d.zhiwu });

                GetNextWxUser(wx, listALL);
                list.Add(wx);
            }

            msg.Result = list;
        }

        public void GetNextWxUser(WXUserBR wx, List<JH_Auth_Branch> listALL)
        {
            var list = (from p in listALL
                        where p.DeptRoot == wx.DeptCode
                        orderby p.DeptShort
                        select new WXUserBR { DeptCode = p.DeptCode, DeptName = p.DeptName }).ToList();

            wx.SubDept = list;
            foreach (var v in list)
            {
                v.DeptUser = new JH_Auth_UserB().GetEntities(d => d.BranchCode == v.DeptCode).ToList().Select(d => new { d.ID, d.UserName, d.UserRealName, d.telphone, d.mobphone, d.zhiwu });
                GetNextWxUser(v, listALL);
            }
        }

        /// <summary>
        /// P1:手机号，多个逗号(,)隔开
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg">手机号，多个逗号(,)隔开</param>
        /// <param name="P1"></param>
        /// <param name="P2">短信内容</param>
        /// <param name="UserInfo"></param>
        public void SENDSMS(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            CommonHelp.SendSMS(P1, P2);
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void GETUSERINFO(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            msg.Result = UserInfo;
        }

        //考勤配置
        public void ADDKQPZ(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            JH_Auth_KQ cc = JsonConvert.DeserializeObject<JH_Auth_KQ>(P1);

            if (new JH_Auth_KQB().GetEntities(d => d.Type == "1").ToList().Count > 0)
            {
                new JH_Auth_KQB().Update(cc);
            }
            else
            {
                new JH_Auth_KQB().Insert(cc);
            }

            msg.Result = cc;
        }

        public void GETKQPZ(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            msg.Result = new JH_Auth_KQB().GetEntity(d => d.Type == "1");
        }


        /// 上传图片文件 
        /// </summary> 
        /// <param name="url">提交的地址</param> 
        /// <param name="poststr">发送的文本串   比如：user=eking&pass=123456  </param> 
        /// <param name="fileformname">文本域的名称  比如：name="file"，那么fileformname=file  </param> 
        /// <param name="filepath">上传的文件路径  比如： c:\12.jpg </param> 
        /// <param name="fileType">上传的文件类型 比如：image/jpeg</param> 
        /// <param name="cookie">cookie数据</param> 
        /// <param name="refre">头部的跳转地址</param> 
        /// <returns></returns> 
        public void POSTFILE(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)//string url, string poststr, string fileformname, string filepath, string fileType, string cookie, string refre)
        {
            string serverfile = WXHelp.GetMediaFile(P1);

            //string url = context.Request["url"];
            string fileToUpload = serverfile; //context.Server.MapPath("/images/") + "buttonbg.png";  //context.Request["filepath"];
            //string poststr = context.Request["poststr"] ?? "";
            //string fileFormName = context.Request["fileformname"];
            //string fileType = context.Request["fileType"];

            string uploadUrl = WXHelp.FileServerUrl + "fileupload";
            //string fileFormName = fileformname;
            //string contenttype = fileType;
            string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
            HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uploadUrl);
            webrequest.ContentType = "multipart/form-data; boundary=" + boundary;
            webrequest.Method = "POST";
            StringBuilder sb = new StringBuilder();
            //foreach (string c in poststr.Split('&'))
            //{
            //    string[] item = c.Split('=');
            //    if (item.Length != 2)
            //    {
            //        break;
            //    }
            //    string name = item[0];
            //    string value = item[1];
            //    sb.Append("–" + boundary);
            //    sb.Append("\r\n");
            //    sb.Append("Content-Disposition: form-data; name=\"" + name + "\"");
            //    sb.Append("\r\n\r\n");
            //    sb.Append(value);
            //    sb.Append("\r\n");
            //}
            sb.Append("--");
            sb.Append(boundary);
            sb.Append("\r\n");
            sb.Append("Content-Disposition: form-data; name=\"file");
            //sb.Append(fileFormName);
            sb.Append("\"; filename=\"");
            sb.Append(Path.GetFileName(fileToUpload));
            sb.Append("\"");
            sb.Append("\r\n");
            sb.Append("Content-Type: application/octet-stream");
            //sb.Append(contenttype);
            sb.Append("\r\n");
            sb.Append("\r\n");
            string postHeader = sb.ToString();
            byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);
            byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
            FileStream fileStream = new FileStream(fileToUpload, FileMode.Open, FileAccess.Read);
            long length = postHeaderBytes.Length + fileStream.Length + boundaryBytes.Length;
            webrequest.ContentLength = length;
            Stream requestStream = webrequest.GetRequestStream();
            requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
            byte[] buffer = new Byte[(int)fileStream.Length];
            int bytesRead = 0;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                requestStream.Write(buffer, 0, bytesRead);
            }
            requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
            fileStream.Close();
            WebResponse responce = webrequest.GetResponse();
            requestStream.Close();
            using (Stream s = responce.GetResponseStream())
            {
                using (StreamReader sr = new StreamReader(s))
                {
                    string md5 = sr.ReadToEnd();

                    System.IO.FileInfo f = new FileInfo(serverfile);

                    FT_File newfile = new FT_File();
                    newfile.Name = f.Name;
                    newfile.FileMD5 = md5.Replace("\"", "");
                    newfile.FileSize = f.Length.ToString();
                    newfile.FileVersin = 0;
                    newfile.CRDate = DateTime.Now;
                    newfile.CRUser = UserInfo.User.UserName;
                    newfile.UPDDate = DateTime.Now;
                    newfile.UPUser = UserInfo.User.UserName;
                    //newfile.FolderID = int.Parse(P2);
                    newfile.FileExtendName = f.Extension.Substring(1);
                    if (new List<string>() { "pdf", "txt", "html", "doc", "docx", "ppt", "pptx", "mp4", "flv", "ogg" }.Contains(newfile.FileExtendName))
                    {
                        newfile.ISYL = "Y";
                    }

                    new FT_FileB().Insert(newfile);

                    msg.Result = newfile.ID;
                }
            }
        }

    }

    public class WXUserBR
    {
        public int DeptCode { get; set; }
        public string DeptName { get; set; }
        public dynamic DeptUser { get; set; }
        public List<WXUserBR> SubDept { get; set; }
    }

}